<script setup>
import { ref, onMounted, reactive } from 'vue'
import { Search, Delete, EditPen, Operation, Back, Tools } from '@element-plus/icons-vue'
import { animediaAll, mediaDelete, mediaEdit, demosearch, mediaCourse } from "@/utils/api.js";
import { ElMessage, ElMessageBox } from 'element-plus'
import moment from 'moment';

import close from '@/assets/icon/close.svg'
import preVideo from '@/components/common/preVideo.vue';
import play from '@/assets/img/play.png'

const ruleFormRef = ref(null);
const isLabel = ref(false);
const iscurs = ref(true);
const cursL = ref([]);
const isdel = ref(false);
const delArr = ref([]);
const lookVideo = ref(null)
const time = ref('');
const sourceType = ref('');
const keywords = ref('');
const pageNum = ref(1);
const totalElements = ref(0);
const currentPage = ref(1);
const allimg = ref('');
const $moment = moment;
const mdObj = reactive({});
const ruleForm = reactive({
    "label": "",
});
const rules = reactive({
    label: [{ required: true, message: '请填写标注', trigger: 'blur' }]
});


const openlabel = (item) => {
    Object.assign(mdObj, item)
    ruleForm.label = item.label;

    isLabel.value = true;
};

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {

            let params = {
                "mediaId": mdObj.id,
                "isAppShow": mdObj.isAppShow,
                "label": ruleForm.label,
                "lon": "", //经度
                "lat": "", //纬度
                "altitude": "" //海拔
            }

            mediaEdit(params).then((res => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: res.message,
                    })
                    getallm();
                    resetForm(ruleFormRef.value);
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.message,
                    })
                }
            }))


        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields();
    isLabel.value = false;
}


const adddelId = (item) => {
    if (delArr.value.indexOf(item) == -1) {
        delArr.value.push(item)
    } else {
        delArr.value.splice(delArr.value.indexOf(item), 1)
    }
}

const mdmd = async () => {

    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            mediaDelete(delArr.value).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    delArr.value = [];
                    isdel.value = false;
                    getallm();
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })

        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })


}

const fptml = (data) => {
    if (data != null && data != '') {
        let datetime = new Date(data);
        let year = datetime.getFullYear();
        let month = datetime.getMonth() + 1;
        let date = datetime.getDate();
        let Hours = datetime.getHours();
        let Minutes = datetime.getMinutes();
        let Seconds = datetime.getSeconds();

        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (date >= 0 && date <= 9) {
            date = "0" + date;
        }

        return year + "-" + month + "-" + date;
    } else {
        return ""
    }
}

const handleCurrentChange = (val) => {
    delArr.value = [];
    isdel.value = false;
    pageNum.value = val;
    getallm();
};


const pmediaEdit = async (item) => {
    let params = {
        "mediaId": item.id,
        "isAppShow": item.isAppShow,
        "label": item.label,
        "lon": "", //经度
        "lat": "", //纬度
        "altitude": "" //海拔
    }

    await mediaEdit(params)
}

const pmediaCourse = async (item) => {
    let params = {
        "resourceId": "ae165634dd554770a8762aaddb0619b9",
        "fileTypes": [
            "image", 'video'
        ],
        "sourceType": '',
        "time": '',
        "keywords": ''
    }

    let res = await mediaCourse(params)

    cursL.value = res.data;
}

const resp = () => {
    delArr.value = [];
    isdel.value = false;
    pageNum.value = 1;
    currentPage.value = 1;
    getallm();
}

const getallm = async () => {
    let params = {
        "resourceId": 'ae165634dd554770a8762aaddb0619b9',
        "fileTypes": [
            "image", 'video'
        ],
        "pageSize": 24,
        "pageNum": pageNum.value,
        "sourceType": sourceType.value,
        "time": fptml(time.value),
        "keywords": keywords.value
    }
    let res = await animediaAll(params);
    if (res.code == '200') {
        totalElements.value = res.data.totalElements;
        allimg.value = res.data.content;
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        allimg.value = []
    }
}

const getdemo = async () => {
    let params = {
        "imei": "",
        "model": "",
        "systemVersion": "",
        "province": "",
        "city": "",
        "areaId": "",
        "startDate": 2412545541,
        "endDate": 42121214,
        "type": 1
    }
    let res = demosearch(1, 10, params)
}

defineExpose({
    $moment
})

onMounted(() => {
    // getallm();
    getdemo()

})

</script>
<template>
    <div>
        <el-row :gutter="20">
            <el-col :span="4" style="display: flex;justify-content: space-between;">
                <span class="comm-title">照片/视频</span>
                <el-switch size="large" v-model="iscurs" @change="pmediaCourse();" class="ml-2"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #387BFF" inline-prompt
                    active-text="查看列表" inactive-text="查看历程" />
            </el-col>

            <el-col :span="3">
                <el-date-picker v-if="iscurs" style="width: 100%;" v-model="time" type="date" @change="resp()"
                    placeholder="选择日期" size="large" />
            </el-col>
            <el-col :span="3">
                <el-select v-if="iscurs" v-model="sourceType" clearable placeholder="来源" @change="resp()" size="large"
                    style="width: 100%;">
                    <el-option label="红外/实时相机" value="infrared" />
                    <el-option label="本地调查" value="local" />
                    <el-option label="巡护监测" value="patrol" />
                    <el-option label="动物监测" value="supervies" />
                    <el-option label="上传文件" value="upload" />
                    <el-option label="上传点位" value="point" />
                    <el-option label="声纹监测" value="superviesvoice" />
                    <el-option label="其他" value="else" />
                </el-select>
            </el-col>
            <el-col :span="4">
                <el-input v-if="iscurs" v-model="keywords" placeholder="搜索人员、照片标注" style="width: 100%;" size="large"
                    class="input-with-select">
                    <template #append>
                        <el-button @click.stop="resp()" :icon="Search" />
                    </template>
                </el-input>
            </el-col>


            <el-col :span="10" style="text-align: right;">
                <el-button v-if="isdel" type="info" @click="mdmd" plain :icon="Delete" size="large">
                    删除（{{ delArr.length }}）
                </el-button>

                <el-button v-if="isdel" @click="delArr = []; isdel = false" type="info" plain :icon="Delete"
                    size="large">
                    取消删除
                </el-button>
                <el-button v-if="!isdel" @click="isdel = true" type="info" plain :icon="Delete" size="large">
                    批量删除
                </el-button>
                <!-- <el-button type="info" plain :icon="Operation" size="large">
                    查看历程
                </el-button> -->

                <el-button type="info" plain :icon="Back" size="large">
                    返回
                </el-button>
            </el-col>
        </el-row>
        <br>
        <!-- 主容器 -->
        <div class="comm-box" v-if="iscurs">
            <!-- 分页 E-->
            <div class="comm-mv clearfix scol">
                <div v-for="i in allimg" :key="i.id">
                    <el-image style="width: 100%;height: 175px;" :src="i.thumbnail" v-if="i.fileType == 'image'"
                        :zoom-rate="1.2" :preview-src-list="[i.mediaUrl]" />
                    <div @click.stop="lookVideo.open(i.mediaUrl)" style="height: 175px;" class="comm-playlms"
                        v-if="i.fileType == 'video'">
                        <img style="width: 100%;height: 100%;" :src="i.converUrl" alt="">
                        <img style="width: 50px;height:50px;position: absolute;z-index: 2;" :src="play" alt="">
                    </div>

                    <!-- 多选框 -->
                    <input v-if="isdel" class="comm-chedel" @change="adddelId(i.id)" type="checkbox"
                        :checked="delArr.indexOf(i.id) != -1">
                    <!-- 多选框 -->

                    <!-- 设置 -->
                    <div class="setIc">
                        <el-popover placement="top-end" :width="100" trigger="click">
                            <template #reference>
                                <el-icon style="font-size: 20px;">
                                    <Tools />
                                </el-icon>
                            </template>
                            <el-checkbox @change="pmediaEdit(i)" v-model="i.isAppShow" label="移动端可查看" />

                            <el-button style="margin-top: 8px;" @click.stop="openlabel(i)" type="info" plain
                                :icon="EditPen">
                                编辑标注
                            </el-button>

                        </el-popover>
                    </div>
                    <!-- 设置 -->
                    <div class="comm-txt">
                        <div>
                            <span>{{ i.sourceType }}</span>
                            <span>{{ i.label }}</span>
                        </div>
                        <span style="color: #AAAAAA;">@{{ i.identifyUser }}{{
                            $moment(i.time).format('YYYY-MM-DD')
                            }}</span>
                    </div>
                </div>
            </div>
            <div class="ml-page">
                <el-pagination v-model:current-page="currentPage" :page-size="24" background
                    layout="total, prev, pager, next, jumper" :total="totalElements"
                    @current-change="handleCurrentChange" />
            </div>
            <!-- 分页 B-->
        </div>
        <!-- 历程 -->
        <div class="comm-box" v-if="!iscurs">
            <div class="comm-mv clearfix scol">
                <el-timeline style="margin-left: 24px;">
                    <template v-if="true" v-for="(i, index) in cursL" :key="index+i.year">
                        <el-timeline-item color="#387BFF" size="large" :timestamp="`${i.detail.latestDate}  最后发现`"
                            placement="top">
                            <el-card>
                                <div class="comm-mv clearfix">
                                    <div v-for="ies in i.detail.earliestDateRecords" :key="ies.id">
                                        <el-image style="width: 100%;height: 175px;" :src="ies.thumbnail"
                                            v-if="ies.fileType == 'image'" :zoom-rate="1.2"
                                            :preview-src-list="[ies.mediaUrl]" />
                                        <div @click.stop="lookVideo.open(ies.mediaUrl)" style="height: 175px;"
                                            class="comm-playlms" v-if="ies.fileType == 'video'">
                                            <img style="width: 100%;height: 100%;" :src="ies.converUrl" alt="">
                                            <img style="width: 50px;height:50px;position: absolute;z-index: 2;"
                                                :src="play" alt="">
                                        </div>
                                        <div class="comm-txt">
                                            <div>
                                                <span>{{ ies.sourceType }}</span>
                                                <span>{{ ies.label }}</span>
                                            </div>
                                            <span style="color: #AAAAAA;">@{{ ies.identifyUser }}{{
                                                $moment(ies.time).format('YYYY-MM-DD')
                                                }}</span>
                                        </div>
                                    </div>
                                </div>
                            </el-card>
                        </el-timeline-item>
                        <el-timeline-item color="#387BFF" size="large" :timestamp="`${i.detail.mostRecordsDate}  高峰期`"
                            placement="top">
                            <el-card>
                                <div class="comm-mv clearfix">
                                    <div v-for="ies in i.detail.mostRecordsDateRecords" :key="ies.id">
                                        <el-image style="width: 100%;height: 175px;" :src="ies.thumbnail"
                                            v-if="ies.fileType == 'image'" :zoom-rate="1.2"
                                            :preview-src-list="[ies.mediaUrl]" />
                                        <div @click.stop="lookVideo.open(ies.mediaUrl)" style="height: 175px;"
                                            class="comm-playlms" v-if="ies.fileType == 'video'">
                                            <img style="width: 100%;height: 100%;" :src="ies.converUrl" alt="">
                                            <img style="width: 50px;height:50px;position: absolute;z-index: 2;"
                                                :src="play" alt="">
                                        </div>
                                        <div class="comm-txt">
                                            <div>
                                                <span>{{ ies.sourceType }}</span>
                                                <span>{{ ies.label }}</span>
                                            </div>
                                            <span style="color: #AAAAAA;">@{{ ies.identifyUser }}{{
                                                $moment(ies.time).format('YYYY-MM-DD')
                                                }}</span>
                                        </div>
                                    </div>
                                </div>
                            </el-card>
                        </el-timeline-item>
                        <el-timeline-item color="#387BFF" size="large" :timestamp="`${i.detail.earliestDate}  早期发现`"
                            placement="top">
                            <el-card>
                                <div class="comm-mv clearfix">
                                    <div v-for="ies in i.detail.earliestDateRecords" :key="ies.id">
                                        <el-image style="width: 100%;height: 175px;" :src="ies.thumbnail"
                                            v-if="ies.fileType == 'image'" :zoom-rate="1.2"
                                            :preview-src-list="[ies.mediaUrl]" />
                                        <div @click.stop="lookVideo.open(ies.mediaUrl)" style="height: 175px;"
                                            class="comm-playlms" v-if="ies.fileType == 'video'">
                                            <img style="width: 100%;height: 100%;" :src="ies.converUrl" alt="">
                                            <img style="width: 50px;height:50px;position: absolute;z-index: 2;"
                                                :src="play" alt="">
                                        </div>
                                        <div class="comm-txt">
                                            <div>
                                                <span>{{ ies.sourceType }}</span>
                                                <span>{{ ies.label }}</span>
                                            </div>
                                            <span style="color: #AAAAAA;">@{{ ies.identifyUser }}{{
                                                $moment(ies.time).format('YYYY-MM-DD')
                                                }}</span>
                                        </div>
                                    </div>
                                </div>
                            </el-card>
                        </el-timeline-item>
                    </template>
                </el-timeline>
            </div>
        </div>
        <!-- 历程 -->
        <!-- 主容器 B-->
        <!-- 查看视频 -->
        <pre-video ref="lookVideo" />
        <!-- 标注弹窗 -->
        <div class="comm-frm" v-if="isLabel">
            <div class="comm-label">
                <div class="comm-close" @click.stop="resetForm(ruleFormRef)">
                    <img :src="close" alt="">
                </div>
                <div class="qzTitle">
                    <div></div>
                    <span>标注</span>
                </div>
                <div style="height: 16px;"></div>
                <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="top" label-width="80px"
                    class="demo-ruleForm" size="default" status-icon>
                    <el-form-item label="" prop="label">
                        <el-input v-model="ruleForm.label" maxlength="6" show-word-limit size="large"
                            placeholder="请填写标注" />
                    </el-form-item>

                    <el-form-item>
                        <el-button style="background-color:#387BFF;" type="primary" @click="submitForm(ruleFormRef)">
                            确定
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

    </div>
</template>
<style scoped>
.comm-title {
    font-size: 28px;
    font-family: 'CustomFont';
}

.comm-box {
    width: 100%;
    height: calc(100% - 64px);
    overflow: hidden;
}

.comm-mv {
    width: 100%;
    height: calc(100% - 64px);
}


.comm-mv>div {
    float: left;
    height: 275px;
    width: calc((100% - 85px) / 6);
    margin-right: 16px;
    margin-bottom: 16px;
    border: 1px solid #F5F7FA;
    position: relative;
    overflow: hidden;
}

.comm-mv>div>div:nth-child(1) {
    border-radius: 8px;
    overflow: hidden;
}

.comm-mv>div:nth-child(6n) {
    margin-right: 0;
}

.comm-txt {
    line-height: 1.5;
    padding: 0 8px;
    overflow: hidden;
}

.comm-txt>div:nth-child(1) {
    width: 100%;
    font-size: 16px;
    line-height: 2 !important;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.comm-playlms {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    cursor: pointer;
}

.setIc {
    width: 32px;
    height: 32px;
    color: #606266;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 8px;
    top: 160px;
    z-index: 3;
    border-radius: 4px;
    background-color: #fff;
    overflow: hidden;
    cursor: pointer;
}

.comm-frm {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9;
    background-color: rgba(0, 0, 0, .5);
}

.comm-label {
    width: 500px;
    padding: 24px;
    border-radius: 4px;
    background-color: #fff;
    position: relative;
    overflow: hidden;
}

.comm-close {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
}

.comm-chedel {
    width: 26px;
    height: 26px;
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 3;
}
</style>